package com.edgar.baselibrary.utils;

import android.text.TextUtils;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;

/**
 * Created by Admin on 2015/7/11.
 */
public final class  IOUtils{

    private static final String TAG = IOUtils.class.getSimpleName();

    private IOUtils(){}

    public static void closeQuietly(Closeable closeable){
        try{
            if(closeable != null){
                closeable.close();
            }
        } catch (IOException e){
            Log.e(TAG,e.getMessage());
        }
    }

    public static String readString(InputStream is){
        return readString(is,2048,"UTF-8");
    }

    public static String readString(InputStream is,int bufferSize,String charset){
        if(TextUtils.isEmpty(charset)) charset = "UTF-8";
        Reader reader = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            reader = new InputStreamReader(is,charset);
            char[] chars = new char[bufferSize];
            int readLen = 0;
            while ((readLen = reader.read(chars)) != -1){
                stringBuilder.append(chars,0,readLen);
            }
        } catch (IOException e) {
        } finally {
            closeQuietly(reader);
        }
        return stringBuilder.toString();
    }

    public static byte[] readBytes(InputStream is){
        return readBytes(is,2048);
    }

    public static byte[] readBytes(InputStream inputStream,int bufferSize){
        byte[] buffer = new byte[bufferSize];
        int readSize = 0;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            while ((readSize = inputStream.read(buffer)) != -1){
                byteArrayOutputStream.write(buffer,0,readSize);
            }
        } catch (IOException e) {
            Log.e(TAG,e.getMessage());
        } finally {
            closeQuietly(byteArrayOutputStream);
        }
        return byteArrayOutputStream.toByteArray();
    }

    public static void writeStream(InputStream inputStream, OutputStream outputStream){
        byte[] buffer = new byte[1024];
        int len = 0;
        try {
            while ((len = inputStream.read(buffer)) != -1){
                outputStream.write(buffer,0,len);
            }
        } catch (IOException e) {
            Log.e(TAG,e.getMessage());
        }
    }
}